package com.masita.ventanas;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;

import com.masita.logica.Cuota;


public class VAddCuota extends JDialog {

	private Cuota cuota = null;
	private double monto = 0;  

	private JLabel etMonto = new JLabel("Monto de la Entrega");
	private JTextField tMonto = com.masita.util.Utilidad.getDoubleJTextField();
	
	private JButton bAceptar = new JButton("Registrar");
	private JButton bCancelar = new JButton("Cancelar");
	
	public VAddCuota(JDialog p, double m){
		super(p,"Registrar Entrega",true);
		init(m);
	}
	
	private void init(double m){
		this.monto = m;
		
		this.getContentPane().setLayout(null);
		this.getContentPane().add(etMonto);
		etMonto.setBounds(30,15,100,20);
		this.getContentPane().add(tMonto);
		tMonto.setBounds(130,15,40,20);
		tMonto.setText(com.masita.util.Utilidad.getFormatoDouble(String.valueOf(m),2));
		tMonto.addKeyListener(new KeyListener(){
			public void keyPressed(KeyEvent e){
				if( e.getKeyCode() == KeyEvent.VK_ENTER )
					bAceptar.doClick();				
			}
			public void keyReleased(KeyEvent e){}
			public void keyTyped(KeyEvent e){}
		});
		
		this.getContentPane().add(this.bAceptar);
		this.bAceptar.setBounds(20,50,80,20);
		this.bAceptar.addActionListener(new java.awt.event.ActionListener(){
			public void actionPerformed(java.awt.event.ActionEvent e){
				guardarCuota();
			}
		});

		this.getContentPane().add(this.bCancelar);
		this.bCancelar.setBounds(110,50,80,20);
		this.bCancelar.addActionListener(new java.awt.event.ActionListener(){
			public void actionPerformed(java.awt.event.ActionEvent e){
				dispose();
			}
		});
	}
	
	private void guardarCuota(){
		
		double cuota;
		try{
			cuota = Double.parseDouble(this.tMonto.getText());
		}
		catch(Exception e){
			cuota = 0;
		}
		
		if( this.monto < cuota ){
			VentanaMensaje v = new VentanaMensaje(this,"Error","El Monto de la Cuota no puede ser mayor al Saldo Restante",false);
			this.tMonto.setText(this.monto+"");
		}
		else if( cuota == 0){
			VentanaMensaje v = new VentanaMensaje(this,"Error","El Monto de la Cuota no puede ser 0",false);
			this.tMonto.setText(this.monto+"");
		}
		else{
			this.cuota = new Cuota(0,0,0,com.masita.util.Utilidad.getFechaHoy(),cuota,false);
			dispose();
		}
	}
	
	public Cuota getCuota(){
		return this.cuota;
	}

	// TODO MOSTRAR DE LA CLASE ***************************
	public void mostrar(){
		this.setSize(220,110);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		this.setVisible(true);
	}	
	
}
